/**
 * Notes: 资讯后台管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2021-07-11 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const dataUtil = require('../../../../framework/utils/data_util.js');
const util = require('../../../../framework/utils/util.js');
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');

const NewsModel = require('../../model/news_model.js');

class AdminNewsService extends BaseProjectAdminService {


  /**添加资讯 */
  async insertNews({
    title,
    cateId, //分类
    cateName,
    order,
    desc = '',
    forms
  }) {

    try {
      let data = {
        NEWS_TITLE: title,
        NEWS_CATE_ID: cateId,
        NEWS_CATE_NAME: cateName,
        NEWS_ORDER: order,
        NEWS_DESC: desc,
        NEWS_FORMS: forms,
        NEWS_OBJ: dataUtil.dbForms2Obj(forms),
      }

      await NewsModel.insert(data);
      // 返回插入成功的结果
      return {
        code: 0,
        message: '插入新闻资讯成功',
        data
      };
    } catch (error) {
      console.error('[插入新闻资讯失败]', err);
      // 返回错误信息
      return {
        code: -1,
        message: '插入新闻资讯失败：' + err.message,
        data: null
      };
    }

  }

  /**删除资讯数据 */
  async delNews(id) {
    try {
      await NewsModel.del(id);
      return {
          code: 0,
          message: '删除资讯成功',
          data: null
      };
  } catch (err) {
      console.error('[删除资讯失败]', err);
      return {
          code: -1,
          message: '删除资讯失败：' + err.message,
          data: null
      };
  }

  }

  /**获取资讯信息 */
  async getNewsDetail(id) {
    let fields = '*';

    let where = {
      _id: id
    }
    let news = await NewsModel.getOne(where, fields);
    if (!news) return null;

    return news;
  }

  // 更新forms信息
  async updateNewsForms({
    id,
    hasImageForms
  }) {
    try {
      const cloud = cloudBase.getCloud();
      const fileIDs = await Promise.all(hasImageForms.map(async image => {
        const res = await cloud.uploadFile({
          cloudPath: 'news_images/' + dataUtil.getUniqueFileName(image.name),
          fileContent: image.data,
        });
        return res.fileID;
      }));

      const result = await NewsModel.edit(id, {
        NEWS_IMAGES: fileIDs
      });
      return {
        code: 0,
        message: '更新表新闻成功',
        data: result
      };
    } catch (err) {
      console.error('[更新新闻失败]', err);
      return {
        code: -1,
        message: '更新新闻失败：' + err.message,
        data: null
      };
    }

  }


  /**
   * 更新富文本详细的内容及图片信息
   * @returns 返回 urls数组 [url1, url2, url3, ...]
   */
  async updateNewsContent({
    id,
    content // 富文本数组
  }) {

    try{
      let data = {
        NEWS_CONTENT:content,
      }
     
     let res= await  NewsModel.edit(id,data)
          // 返回插入成功的结果
          return {
            code: 0,
            message: '修改内容成功',
            res
          };
    }catch(error) {
      console.error('[修改内容失败]', err);
      // 返回错误信息
      return {
          code: -1,
          message: '修改内容失败：' + err.message,
          data: null
      };
    }

  }

  /**
   * 更新资讯图片信息
   * @returns 返回 urls数组 [url1, url2, url3, ...]
   */
  async updateNewsPic({
    id,
    imgList // 图片数组
  }) {
    try{
      let data = {
        NEWS_PIC:imgList,
      }
     
      await  NewsModel.edit(id,data)
          // 返回插入成功的结果
          return {
            code: 0,
            message: '修改图片成功',
            data
          };
    }catch(error) {
      console.error('[修改图片成功失败]', err);
      // 返回错误信息
      return {
          code: -1,
          message: '修改图片成功失败：' + err.message,
          data: null
      };
    }


  }


  /**更新资讯数据 */
  async editNews({
    id,
    title,
    cateId, //分类
    cateName,
    order,
    desc = '',
    forms
  }) {

    try {
      let data = {
        NEWS_TITLE: title,
        NEWS_DESC: desc,
        ADMIN_PHONE: phone,
        NEWS_CATE_ID: cateId,
        NEWS_CATE_NAME: cateName,
        NEWS_ORDER: order,
        NEWS_OBJ: dataUtil.dbForms2Obj(forms),
        NEWS_FORMS: forms
      }

      await NewsModel.edit(id, data)
      // 返回插入成功的结果
      return {
        code: 0,
        message: '修改新闻资讯成功',
        data
      };
    } catch (error) {
      console.error('[修改新闻资讯失败]', err);
      // 返回错误信息
      return {
        code: -1,
        message: '修改管理员失败：' + err.message,
        data: null
      };
    }

  }

  /**取得资讯分页列表 */
  async getAdminNewsList({
    search, // 搜索条件
    sortType, // 搜索菜单
    sortVal, // 搜索菜单
    orderBy, // 排序
    whereEx, //附加查询条件
    page,
    size,
    isTotal = true,
    oldTotal
  }) {

    orderBy = orderBy || {
      'NEWS_ORDER': 'asc',
      'NEWS_ADD_TIME': 'desc'
    };
    let fields = 'NEWS_TITLE,NEWS_DESC,NEWS_CATE_ID,NEWS_CATE_NAME,NEWS_EDIT_TIME,NEWS_ADD_TIME,NEWS_ORDER,NEWS_STATUS,NEWS_CATE2_NAME,NEWS_VOUCH,NEWS_QR,NEWS_OBJ';

    let where = {};
    where.and = {
      _pid: this.getProjectId() //复杂的查询在此处标注PID
    };

    if (util.isDefined(search) && search) {
      where.or = [{
        NEWS_TITLE: ['like', search]
      }, ];

    } else if (sortType && util.isDefined(sortVal)) {
      // 搜索菜单
      switch (sortType) {
        case 'cateId': {
          where.and.NEWS_CATE_ID = String(sortVal);
          break;
        }
        case 'status': {
          where.and.NEWS_STATUS = Number(sortVal);
          break;
        }
        case 'top': {
          where.and.NEWS_ORDER = 0;
          break;
        }
        case 'sort': {
          orderBy = this.fmtOrderBySort(sortVal, 'NEWS_ADD_TIME');
          break;
        }

      }
    }

    return await NewsModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
  }

  /**修改资讯状态 */
  async statusNews(id, status) {
    try {
      let data = {
        NEWS_STATUS: status,
      }

      await NewsModel.edit(id, data)
      // 返回插入成功的结果
      return {
        code: 0,
        message: '修改新闻状态成功',
        data
      };
    } catch (error) {
      console.error('[修改新闻状态失败]', err);
      // 返回错误信息
      return {
        code: -1,
        message: '修改新闻状态失败：' + err.message,
        data: null
      };
    }
  }

  /**置顶与排序设定 */
  async sortNews(id, sort) {
    try {
      let data = {
        NEWS_ORDER: sort,
      }

      await NewsModel.edit(id, data)
      // 返回插入成功的结果
      return {
        code: 0,
        message: '修改新闻置顶成功',
        data
      };
    } catch (error) {
      console.error('[修改新闻置顶失败]', err);
      // 返回错误信息
      return {
        code: -1,
        message: '修改新闻置顶失败：' + err.message,
        data: null
      };
    }
  }
}

module.exports = AdminNewsService;